#include "tooltipsbutton.h"

#include "toolutils.h"
#include <QPropertyAnimation>
#include <QEventLoop>

ToolTipsButton::ToolTipsButton(QWidget* parent, QWidget* toolTips)
    : QPushButton(parent)
    , mToolTips(toolTips)
{
}


void ToolTipsButton::SetToolTips(QWidget* toolTips)
{
    mToolTips = toolTips;
}

QWidget* ToolTipsButton::ToolTips() const {
    return mToolTips;
}


void ToolTipsButton::enterEvent(QEnterEvent *event)
{
    if (mToolTips == nullptr || mToolTips->isVisible())
        return;

    const auto globalPos = mapToGlobal(QPoint(0, 0));
    const auto buttonRect = rect();
    const auto toolTipsRect = mToolTips->rect();

    const int x = globalPos.x() + (buttonRect.width() - toolTipsRect.width()) / 2;
    const int y = globalPos.y() - toolTipsRect.height() - 5;

    mToolTips->show();
    ToolUtils::ShowMoveAnimation(mToolTips, QPoint(x, y + 10), QPoint(x, y), 200);
    mTimerId = startTimer(250);
}

void ToolTipsButton::timerEvent(QTimerEvent *event)
{
    if (mToolTips == nullptr || !mToolTips->isVisible()) {
        return;
    }

    const QPoint cursorPos = QCursor::pos();
    const QRect buttonRect = rect();
    const QRect sliderRect = mToolTips->geometry();
    const QPoint buttonGlobalPos = mapToGlobal(QPoint(0, 0));
    const QRect areaRect(
        sliderRect.left(),
        sliderRect.top(),
        sliderRect.width(),
        buttonGlobalPos.y() + buttonRect.height() - sliderRect.top());

    if (!areaRect.contains(cursorPos)) {
        killTimer(mTimerId);
        mToolTips->hide();
    }
}
